package com.nbcio.modules.erp.price.controller;

import com.nbcio.common.core.domain.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nbcio.modules.erp.material.domain.ErpMaterial;
import com.nbcio.modules.erp.material.mapper.ErpMaterialMapper;
import com.nbcio.modules.erp.price.domain.ErpPrice;
import com.nbcio.modules.erp.price.mapper.ErpPriceMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "价格查询")
@RestController
@RequestMapping("/erp/price")
@RequiredArgsConstructor
public class ErpPriceController {

    private final ErpMaterialMapper materialMapper;
    private final ErpPriceMapper priceMapper;

    // 默认价：优先匹配 partyId 指定价格，其次 partyId 为空的通用价格；时间匹配区间（包含当天）
    @GetMapping("/default")
    public R<Map<String, Object>> getDefault(@RequestParam String billType,
                                             @RequestParam String materialId,
                                             @RequestParam(required = false) String partyId,
                                             @RequestParam(required = false) String uomId) {
        Long mid = Long.parseLong(materialId);
        Long pid = (partyId == null || partyId.isEmpty()) ? null : Long.parseLong(partyId);
        Long uid = (uomId == null || uomId.isEmpty()) ? null : Long.parseLong(uomId);
        var now = java.time.LocalDateTime.now();
        LambdaQueryWrapper<ErpPrice> qw = new LambdaQueryWrapper<>();
        qw.eq(ErpPrice::getBillType, billType)
          .eq(ErpPrice::getMaterialId, mid)
          .le(ErpPrice::getStartTime, now)
          .and(w -> w.ge(ErpPrice::getEndTime, now).or().isNull(ErpPrice::getEndTime))
          .orderByDesc(ErpPrice::getUomId) // uomId优先（非空优先）
          .orderByDesc(ErpPrice::getPartyId) // partyId优先
          .last("limit 1");
        if (pid != null) {
            qw.and(w -> w.eq(ErpPrice::getPartyId, pid).or().isNull(ErpPrice::getPartyId));
        } else {
            qw.isNull(ErpPrice::getPartyId);
        }
        if (uid != null) {
            qw.and(w -> w.eq(ErpPrice::getUomId, uid).or().isNull(ErpPrice::getUomId));
        } else {
            qw.isNull(ErpPrice::getUomId);
        }
        ErpPrice p = priceMapper.selectOne(qw);
        ErpMaterial m = materialMapper.selectById(mid);
        Map<String, Object> ret = new HashMap<>();
        ret.put("price", p == null || p.getPrice() == null ? BigDecimal.ZERO : p.getPrice());
        BigDecimal taxRate = p == null || p.getTaxRate() == null ? (m == null ? null : m.getTaxRate()) : p.getTaxRate();
        ret.put("taxRate", taxRate);
        ret.put("matched", p != null);
        ret.put("taxIncluded", p == null || p.getTaxIncluded() == null ? 1 : p.getTaxIncluded());
        ret.put("matchedUom", p != null && p.getUomId() != null);
        return R.ok(ret);
    }
}


